package main

import (
	"context"
	"fmt"
	"go_final/mxshop_srvs/goods_srv/model"
	"strconv"

	"github.com/olivere/elastic/v7"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func main() {
	dsn := "root:root@tcp(120.24.67.46:4306)/mxshop_goods_srv?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		fmt.Println("err", err)
	}

	//_ = db.AutoMigrate(
	//	&model.Category{},
	//	&model.Brand{},
	//	&model.GoodsCategoryBrand{},
	//	&model.Banner{},
	//	&model.Good{})
	mysqlGoodsData2Es(db)
}

func mysqlGoodsData2Es(db *gorm.DB) {
	// 初始化一个连接
	url := "http://120.24.67.46:9200"
	// 这里必须将sniff设置为false, 因为使用olivere/elastic连接elasticsearch时, 发现连接地址命名输入的时候是网址
	// 但是连接时会自动转换成内网地址或者docker中的ip地址, 导致服务连接不上
	client, err := elastic.NewClient(elastic.SetURL(url), elastic.SetSniff(false))
	if err != nil {
		// Handle error
		panic(err)
	}

	var goodsList []model.Good
	db.Find(&goodsList)
	for _, goods := range goodsList {
		_, err := client.Index().
			Index("mygoods").
			Id(strconv.Itoa(int(goods.ID))).
			BodyJson(model.EsGoods{
				ID:          goods.ID,
				CategoryID:  goods.CategoryID,
				BrandID:     goods.BrandID,
				OnSale:      goods.OnSale,
				ShipFree:    goods.ShipFree,
				IsNew:       goods.IsNew,
				IsHot:       goods.IsHot,
				Name:        goods.Name,
				ClickNum:    goods.ClickNum,
				SoldNum:     goods.SoldNum,
				FavNum:      goods.FavNum,
				MarketPrice: goods.MarketPrice,
				GoodBrief:   goods.GoodsBrief,
				ShopPrice:   goods.ShopPrice,
			}).
			Do(context.Background())
		if err != nil {
			// Handle error
			panic(err)
		}
	}
}
